<template>
    <div class="containers container">
        <div class="container top-return">
            <div class="inline-block">
                <el-page-header @back="goBack" :content="currentItem.title"></el-page-header>
            </div>
        </div>
        <div class="container spc">
            <el-form ref="formRef" :model="currentItem.rowData" :rules="rules" label-width="150px" class="demo-ruleForm">
                <!-- 产品信息 -->
                <div class="title head-title bottom-border">
                    产品信息
                </div>

                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="产品代码">
                            <el-input v-model="currentItem.rowData!.productCode" placeholder="请输入产品代码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="产品名称" prop="productName">
                            <el-input v-model="currentItem.rowData!.productName" placeholder="请输入产品名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="系列" prop="classifyId">
                            <!-- <el-input v-model="currentItem.rowData!.classifyId" placeholder="请输入系列分类" /> -->
                            <MySelect v-model="currentItem.rowData.classifyId" :request-api="listWithFather"
                                :fieldNames="memberFiled" :data="currentItem"
                                :initParam="{ pageNum: 1, pageSize: 99999, fatherName: '产品系列' }" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="供应商" prop="supplierId">
                            <!-- <el-input v-model="currentItem.rowData!.supplierId" placeholder="请输入供应商" /> -->
                            <MySelect v-model="currentItem.rowData.supplierId" :request-api="listSupplier"
                                placeholder="请选择所属供应商"
                                :fieldNames="{ label: 'supplierName', value: 'id', labelName: '', autoLable: false }"
                                :data="currentItem" :initParam="{ pageNum: 1, pageSize: 99999 }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="产品分类" prop="category">
                            <!-- <el-input v-model="currentItem.rowData!.category" placeholder="请输入产品分类" /> -->
                            <MySelect v-model="currentItem.rowData.category" :request-api="listWithFather"
                                :fieldNames="{ label: 'childName', value: 'childName', labelName: '', autoLable: false }"
                                :data="currentItem" :initParam="{ pageNum: 1, pageSize: 99999, fatherName: '产品分类' }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="寄样尺寸">
                            <el-input v-model="currentItem.rowData!.dimensions" placeholder="请输入寄样尺寸" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="一级系列" prop="oneLevelSeries">
                            <el-select v-model="currentItem.rowData.oneLevelSeries" placeholder="请选择一级系列" clearable>
                                <el-option label="臻品系列" value="臻品系列" />
                                <el-option label="悦美系列" value="悦美系列" />
                                <el-option label="特能系列" value="特能系列" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row class="el-rows">
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="currentItem.rowData.status">
                                <el-radio :key="0" :label="0" :value="0">在售</el-radio>
                                <el-radio :key="1" :label="1" :value="1">停售</el-radio>
                                <el-radio :key="2" :label="2" :value="2">新品</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="el-rows">
                    <el-col :span="12">
                        <el-form-item label="产品描述" prop="productDesc">
                            <editor v-model="currentItem.rowData.productDesc" :min-height="192" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="title head-title bottom-border">
                    详细规格
                </div>

                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="材质" prop="material">
                            <!-- <el-input v-model="currentItem.rowData!.material" placeholder="请输入材质" /> -->
                            <MySelect v-model="currentItem.rowData.material" :request-api="listWithFather"
                                :fieldNames="{ label: 'childName', value: 'childName', labelName: '', autoLable: false }"
                                :data="currentItem" :initParam="{ pageNum: 1, pageSize: 99999, fatherName: '产品材质' }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="颜色">
                            <!-- <el-input v-model="currentItem.rowData!.color" placeholder="请输入颜色" /> -->
                            <MySelect v-model="currentItem.rowData.color" :request-api="listWithFather"
                                :fieldNames="{ label: 'childName', value: 'childName', labelName: '', autoLable: false }"
                                :data="currentItem" :initParam="{ pageNum: 1, pageSize: 99999, fatherName: '产品颜色' }" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="风格" prop="style">
                            <!-- <el-input v-model="currentItem.rowData!.style" placeholder="请输入风格" /> -->
                            <MySelect v-model="currentItem.rowData.style" :request-api="listWithFather"
                                :fieldNames="{ label: 'childName', value: 'childName', labelName: '', autoLable: false }"
                                :data="currentItem" :initParam="{ pageNum: 1, pageSize: 99999, fatherName: '产品风格' }" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="宽度/cm" prop="productWidth">
                            <el-input v-model="currentItem.rowData!.productWidth" placeholder="请输入宽度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="长度/m" prop="productLength">
                            <el-input v-model="currentItem.rowData!.productLength" placeholder="请输入长度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="厚度/mm" prop="productThickness">
                            <el-input v-model="currentItem.rowData!.productThickness" placeholder="请输入厚度" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="title head-title bottom-border">
                    产品拍照采样
                </div>
                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="采样" prop="productUrl">
                            <!-- 条件渲染：存在数据时显示上传组件，否则显示按钮 -->
                            <template v-if="currentItem.rowData?.productUrlOriginal">
                                <ImageUpload v-model="currentItem.rowData!.productUrlOriginal" :limit="1"
                                    :isShowTip="false" />
                            </template>
                            <template v-else>
                                <el-button type="primary" @click="showSampleDialog = true">点击上传采样</el-button>
                            </template>

                            <!-- <ImageUpload v-model="currentItem.rowData!.productUrl" :limit="1" :isShowTip="false" /> -->
                        </el-form-item>
                    </el-col>
                </el-row>


                <!-- 新增采样弹窗 -->
                <el-dialog v-model="showSampleDialog" title="产品采样上传" width="50%" v-if="showSampleDialog">
                    <div class="video-container">
                        <HLSPlayer v-show="!capturedImage" ref="hlsPlayer" :src="hlsSrc" :autoplay="true" />
                        <img v-if="capturedImage" :src="capturedImage" class="captured-image" />
                    </div>

                    <template #footer>
                        <el-button @click="handleRecapture">重新采集</el-button>
                        <!-- 新增旋转按钮 -->
                        <el-button type="text" @click="handleRotate(90)" v-if="capturedImage">
                            <el-icon>
                                <Refresh />
                            </el-icon> 旋转
                        </el-button>
                        <el-button type="primary" @click="handleCapture">拍照</el-button>
                        <el-button type="success" @click="handleConfirm">确定</el-button>
                    </template>
                </el-dialog>
                <div class="title head-title bottom-border">
                    产品设计图上传（用于展示）
                </div>
                <el-row class="el-rows">
                    <el-col :span="8">
                        <el-form-item label="设计图">
                            <ImageUpload v-model="currentItem.rowData!.productDesign" :limit="1" :isShowTip="false" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="bot-pos-submit">
            <el-button class="simple-btn" @click="goBack">关闭</el-button>
            <el-button class="standard-btn" v-if="currentType != '查看'" @click="submitForm">提交</el-button>
        </div>

        <!-- <MyDiolg ref="dialogRef" /> -->
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, toRefs, defineProps } from "vue";
import Compressor from 'compressorjs';
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
// import MyDiolg from "./Form.vue";
import {
    listWithFather
} from "@/api/zc/classification";
import {
    listSupplier
} from "@/api/zc/SupplierMagment";
import { getToken } from "@/utils/auth";
import { base64ToFile } from '@/utils/ruoyi';
import axios from 'axios';
import HLSPlayer from '@/components/HLSPlayer/index.vue';
import { ElMessage } from "element-plus";
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/uploadFile"); // 上传的图片服务器地址
const headers = ref({
    Authorization: "Bearer " + getToken()
});
// const hlsSrc = ref("http://tlc.gzvst.top/hls/test/index.m3u8");
const hlsSrc = ref("http://172.16.1.100:9008/hls/test/index.m3u8");
let memberFiled = { label: "childName", value: "id", labelName: "childName", autoLable: false };
const activeName = ref('first')
const dialogRef = ref(null);
const handleClick = (tab: any, event: Event) => {
    console.log(tab, event)
}
const formRef = ref();
const emit = defineEmits(["changeItem"]);
interface Props {
    currentItem: any;
    currentType: string;
}
const goBack = () => {
    emit("changeItem", "0");
};
// 新增弹窗控制变量
const showSampleDialog = ref(false);

// 新增上传回调（可选，用于关闭弹窗）
const handleSampleUpload = () => {
    showSampleDialog.value = false; // 上传成功后关闭弹窗
};

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<Props>(), {
    currentItem: {
        rowData: {},
        api: null,
    },
    currentType: "",
});
//提交
const submitForm = async () => {
    formRef.value!.validate(async (valid) => {
        if (!valid) return;
        try {
            await props.currentItem.api({
                ...props.currentItem.rowData
            });
            ElMessage.success({ message: `${props.currentType}成功！` });
            goBack();
        } catch (error) {
            console.log(error);
        }
    });
};
const dialogCallBack = (data: any, index: number | null) => {
    console.log("回调", data);
    console.log("index", index);
    // 修改点：判断 index 是否为非 null（包括 0 等数字情况）
    if (index !== null) {
        props.currentItem.rowData.zcSupplierCertList[index] = data;
    } else {
        props.currentItem.rowData.zcSupplierCertList.push(data);
    }
};
const openDiolg = (title: string, row: any, index: number | null) => {
    const params = {
        title,
        isView: title === "查看",
        rowData: { ...row },
        api: title === "新增" ? dialogCallBack : title === "修改" ? dialogCallBack : undefined,
        index: index
        // getTableList: proTable.value?.getTableList,
    };
    dialogRef.value?.acceptParams(params);
};

// 新增旋转处理方法（顺时针旋转90度）
const handleRotate = (degrees: number) => {
    if (!capturedImage.value) return;

    const img = new Image();
    img.src = capturedImage.value;

    img.onload = () => {
        // 创建Canvas并设置旋转后的尺寸（宽高交换）
        const canvas = document.createElement('canvas');
        canvas.width = img.height;
        canvas.height = img.width;

        const ctx = canvas.getContext('2d')!;
        // 旋转画布（原点移至中心，旋转后绘制）
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.rotate((degrees * Math.PI) / 180);
        ctx.drawImage(img, -img.width / 2, -img.height / 2);

        // 更新捕获的图片为旋转后的Base64
        capturedImage.value = canvas.toDataURL('image/png');
    };
};

//表单验证
const rules = reactive({
    productCode: [
        { required: true, message: '产品代码不能为空', trigger: ['blur', 'change'] }
    ],
    productName: [
        { required: true, message: '产品名称不能为空', trigger: ['blur', 'change'] }
    ],
    supplierId: [
        { required: true, message: '请选择供应商', trigger: 'change' }
    ],
    classifyId: [
        { required: true, message: '请选择产品系列', trigger: 'change' }
    ],
    category: [
        { required: true, message: '请选择产品分类', trigger: 'change' }
    ],
    dimensions: [
        { required: true, message: '寄样尺寸不能为空', trigger: ['blur', 'change'] }
    ],
    productDesign: [
        { required: true, message: '请上传产品设计图', trigger: 'change' }
    ],
    productUrl: [
        { required: true, message: '请上传产品采样图', trigger: 'change' }
    ],
    color: [
        { required: true, message: '颜色不能为空', trigger: ['blur', 'change'] }
    ]
});

const hlsPlayer = ref(null)
const capturedImage = ref('')

// const handleCapture = () => {
//     if (hlsPlayer.value) {
//         // 创建canvas捕获视频帧
//         const videoElement = hlsPlayer.value.$el.querySelector('video')
//         if (videoElement) {
//             const canvas = document.createElement('canvas')
//             canvas.width = videoElement.videoWidth
//             canvas.height = videoElement.videoHeight
//             const ctx = canvas.getContext('2d')
//             ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height)
//             capturedImage.value = canvas.toDataURL('image/png')
//         }
//     }
// }

const handleCapture = () => {
    if (hlsPlayer.value) {
        const videoElement = hlsPlayer.value.$el.querySelector('video');
        if (videoElement) {
            // 获取视频原始尺寸（实际像素）
            const videoWidth = videoElement.videoWidth;
            const videoHeight = videoElement.videoHeight;

            // 获取视频在页面中的显示尺寸（受容器缩放影响）
            const displayWidth = videoElement.clientWidth;
            const displayHeight = videoElement.clientHeight;

            // 计算水平/垂直缩放比例（显示尺寸 / 原始尺寸）
            const scaleX = displayWidth / videoWidth;
            const scaleY = displayHeight / videoHeight;

            // CSS虚线框的偏移量（容器显示尺寸的px）
            const cssOffset = 20; // 对应CSS的top:20px; left:20px等

            // 转换为原始像素的偏移量（CSS的px / 缩放比例）
            const cropX = cssOffset / scaleX;
            const cropY = cssOffset / scaleY;

            // 计算裁剪区域的原始像素尺寸（容器显示的有效宽度/高度 / 缩放比例）
            const cropWidth = (displayWidth - cssOffset * 2) / scaleX;
            const cropHeight = (displayHeight - cssOffset * 2) / scaleY;

            // 创建Canvas并裁剪
            const canvas = document.createElement('canvas');
            canvas.width = cropWidth;
            canvas.height = cropHeight;
            const ctx = canvas.getContext('2d');

            ctx.drawImage(
                videoElement,
                cropX, cropY,       // 原始视频中的裁剪起点（转换后）
                cropWidth, cropHeight, // 原始视频中的裁剪尺寸（转换后）
                0, 0,               // Canvas绘制起点
                cropWidth, cropHeight  // Canvas绘制尺寸
            );

            capturedImage.value = canvas.toDataURL('image/png');
        }
    }
};

const handleRecapture = () => {
    capturedImage.value = ''
}

const processImage = async (file: File): Promise<File> => {
    return new Promise((resolve) => {
        new Compressor(file, {
            quality: 0.65,          // 适当降低质量到65%
            width: 400,             // 适当提高宽度到400px
            height: 400,            // 保持宽高比
            convertSize: 1024000,   // 超过1MB的图片才转换
            mimeType: 'image/webp', // 强制使用WebP格式
            success(result) {
                const thumbFile = new File([result], `thumb_${Date.now()}.webp`, {
                    type: 'image/webp'
                })
                resolve(thumbFile)
            }
        })
    })
}
const handleConfirm = async () => {
    if (!capturedImage.value) {
        ElMessage.warning('请先拍照采集')
        return
    }

    try {
        console.log("原始图片数据:", capturedImage.value)
        const file = base64ToFile(capturedImage.value, `sample_${Date.now()}.png`, 'image/png')
        const thumbFile = await processImage(file)

        console.log(`压缩效果: ${(file.size / 1024).toFixed(2)}KB → ${(thumbFile.size / 1024).toFixed(2)}KB`)

        // 并行上传原始图和缩略图
        const [originalRes, thumbRes] = await Promise.all([
            axios.post(uploadUrl.value, createFormData(file), { headers: headers.value }),
            axios.post(uploadUrl.value, createFormData(thumbFile), { headers: headers.value })
        ])

        if (originalRes.data.code === 200 && thumbRes.data.code === 200) {
            props.currentItem.rowData = {
                ...props.currentItem.rowData,
                productUrl: thumbRes.data.data,
                productUrlOriginal: originalRes.data.data
            }
            ElMessage.success('图片上传成功')
            showSampleDialog.value = false
        } else {
            throw new Error('上传失败')
        }
    } catch (error) {
        console.error('上传出错:', error)
        ElMessage.error('图片上传失败，请重试')
    }
}

// 辅助函数：创建FormData
const createFormData = (file: File): FormData => {
    const formData = new FormData()
    formData.append('file', file)
    return formData
}
</script>
<style lang="scss" scoped>
.video-container {
    position: relative;
    width: 100%;
    height: 400px;
}

.captured-image {
    width: 100%;
    height: 400px;
    object-fit: contain;
    background-color: #f5f5f5;
}

.bot-pos-submit {
    position: fixed;
    height: 60px;
    background: white;
    width: calc(100vw - 252px);
    bottom: 0px;
    text-align: center;
    line-height: 60px;
    z-index: 999;
}

/* 卡片容器样式 */
// .el-rows {
//     display: flex;
//     flex-wrap: wrap;
//     margin: -10px;
// }

// .el-col {
//     padding: 10px;
// }

/* 卡片样式 */
.my-card {
    display: flex;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    height: 100%;
}

.my-card:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    transform: translateY(-3px);

}

.left-img {
    flex-shrink: 0;
    margin-right: 15px;
}

.left-img img {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    object-fit: cover;
}

.right-info {
    flex-grow: 1;
}

.right-info-title {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
}

.right-info-title-left {
    display: flex;
    flex-direction: column;
}

.right-info-title-left span:first-child {
    font-weight: 600;
    font-size: 14px;
    color: #303133;
    margin-bottom: 4px;
}

.right-info-title-left span:last-child {
    font-size: 12px;
    color: #909399;
}

.card-actions {
    display: flex;
    align-items: center;
}


.card-actions .el-button {
    padding: 4px;
    margin-left: 5px;
    font-size: 16px;
}
</style>